import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, TextInput,
	PixelRatio, Platform, ScrollView, Modal, FlatList, Alert
} from 'react-native';
import { GLOBAL } from '../../../../../../config/global';
import { style } from '../../../../../../theme/style';
import { productSelectStyle } from '../../../_common/style';
import HTTP from '../../../../../../utils/http';
import { PageStatusIndex } from '../../../../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../../../../config/api';

const scale = GLOBAL.SCALE;
let optionPicSourse = require('../../../../../../imgs/global/option.png');
let selectedPicSourse = require('../../../../../../imgs/global/success.png');
let searchIcon = require('../../../../../../imgs/customer/searchLeft.png');


/*
	modalVisible : 控制弹框显示隐藏  值: boolean ( true ,false)
	chang : 企业变更 特别展示  值: boolean ( true ,false)
	data : 商品数据  值 : JSON对象
	leftBtnIcon : 头部筛选左侧图标。类型 boolean：true显示，默认为false
	widthoutTop : 是否展示头部。类型 boolean：true 时不显示头部筛选及操作按钮，默认为false
	renderLeft : 自定义头部-左侧图形。默认 this._renderLeftBtns()
	renderRight : 自定义头部-右侧图形。默认 this._renderRightBtns()
	middleContent : 自定义头部-中间图形。默认 this._renderFilterContent()
	leftBtnsList : 默认头部-左侧按钮。类型 array：[{ btnText:'确认添加',btnFun:()=>{console.log(1)}}]，不传则不展示
	rightBtnsList : 默认头部-右侧按钮。类型 array：[{ btnText:'确认添加',btnFun:()=>{console.log(1)}}]，不传则不展示
*/


export class ProductSelect extends Component {

	constructor(props) {
		super(props);
		let { modalVisible, data, single } = this.props;
		single = single ? (single == 'true' ? true : false) : true;
		this.state = {
			modalVisible: modalVisible || false,
			sideDataSource: data || [], // 一级数据
			mainDataSource: data && data[0] && data[0].goodsList || [], // 二级数据
			sideCheckData: [], // 一级数据回显
			mainCheckData: [],   // 二级数据回显
			status: 'loading',  // 数据加载状态
			single,
		}
		this.goodsData = {}; // 参数收集
		console.log('商品弹框-000000')
	}

	componentWillMount () {
		let { sideDataSource } = this.state;
		if (!sideDataSource.length) return;
		this._sideCheckFn(sideDataSource[0].goodsCateCode);
	}

	componentWillReceiveProps (props) {
		console.log('props', props);
		let { data } = props;
		this.setState({
			sideDataSource: data || [], // 一级数据
			mainDataSource: data && data[0] && data[0].goodsList || [], // 二级数据
		})
	}

	// 一级勾选
	_sideCheckFn = (goodsCateCode) => {
		let { sideDataSource, mainDataSource, sideCheckData } = this.state;
		sideDataSource && sideDataSource.map((item) => {
			if (item.goodsCateCode == goodsCateCode) {
				sideCheckData[0] = { goodsCode: item.goodsCateCode, goodsName: item.goodsCateName };
				item.selected = true;
				mainDataSource = item.goodsList;
			} else {
				item.selected = false;
			}
			return item;
		})
		this.setState({
			sideDataSource,
			mainDataSource,
			sideCheckData
		})
	}

	// 二级勾选  [{goodsId:'1',goodsName:'阿三'}]
	_mainCheckFn = (childrenGoodsId, childrenGoodsName, goodsItem) => {
		let { single, mainCheckData, sideCheckData, sideDataSource } = this.state;
		let isRemove = mainCheckData && mainCheckData.some((item) => {
			return item.goodsCode == childrenGoodsId
		})

		if (isRemove) {  // 移除
			if (single) { // 单选
				mainCheckData = [];
				//sideCheckData = [];
			} else { // 多选
				mainCheckData = mainCheckData && mainCheckData.filter((item) => {
					if (item.goodsCode != childrenGoodsId) {
						return item;
					}
				})
			}
		} else {  // 添加
			if (single) { // 单选
				mainCheckData[0] = { goodsCode: childrenGoodsId, goodsName: childrenGoodsName, goodsItem };
			} else { // 多选
				mainCheckData.push({ goodsCode: childrenGoodsId, goodsName: childrenGoodsName, goodsItem });
			}
		}

		if (mainCheckData.length == 0) {
			sideDataSource && sideDataSource.map((item) => {
				item.index = 0;
				item.goodsList && item.goodsList.map((items) => {
					items.selected = false;
					return items;
				})
			})
		} else {
			sideDataSource && sideDataSource.map((item) => {
				item.index = 0;
				item.goodsList && item.goodsList.map((items) => {
					let lsOnoff = mainCheckData && mainCheckData.some((a) => {
						return a.goodsCode == items.goodsCode
					})
					if (lsOnoff) {
						items.selected = true;
						item.index++;   ///  --------------------------
						return items;
					} else {
						items.selected = false;
						return items;
					}
				})
				return item;
			})
		}
		this.setState({
			sideDataSource,
			mainCheckData,
			//sideCheckData
		})
	}

	//根据数据显示第一个数据
	_formattingData (data) {
		if (data && data.length) {
			data[0].selected = true;
			this.setState({
				sideDataSource: data
			}, () => {
				this._sideCheckFn(data[0].goodsCateCode || '');
			})
		} else {
			this.setState({
				sideDataSource: data
			})
		}
	}

	//搜索
	_searchFn = () => {
		let { searchPress } = this.props;
		this.setState({
			mainCheckData: []
		}, async () => {
			//获取数据
			let goodsData = searchPress && await searchPress(this.goodsData);
			//根据数据初始化
			this._formattingData(goodsData, true);
		})
	}

	// 搜索
	_writeFn = async (val) => {
		let searchCode = val.replace(/(^\s*)|(\s*$)/g, "");
		this.goodsData.searchCode = searchCode;
		this._searchFn();
	}

	//二级数据
	_renderMain = (data) => {
		let { change } = this.props;
		const { goodsName, goodsCode, selected, operateType, updateBy, companyName } = data.item;
		let picSource = selected ? selectedPicSourse : optionPicSourse;
		return (
			<TouchableOpacity onPress={() => {
				this._mainCheckFn(goodsCode, goodsName, data.item);
			}} activeOpacity={0.5} style={styles.listMainRow}>
				{/* <Image source={picSource} style={styles.optionPic} /> */}
				<Text style={[styles.listSideText]}>{goodsName}</Text>
				{change && <Text style={[styles.changeText]}>{operateType == 'D' ? '(删)' : operateType == 'C' ? '(增)' : ''}</Text>}
				<Text style={styles.deptText}>{updateBy}{companyName ? `（${companyName}）` : ''}</Text>
				{/* {
                  staffNameList && staffNameList.length ?
                    staffNameList.map((item, index) => {
                      return (<Text style={optionBox ? styles.applyStaffName : styles.applyStaffNameNO} key={index}>{item}</Text>)
                    }) : null
                } */}
			</TouchableOpacity>
		);
	}

	//一级数据
	_renderSide = (side) => {
		let { goodsCateName, goodsCateCode, goodsList, selected, index } = side.item;
		// let curStyle = (selected) ? styles.listSideRowCur : null;
		let { single } = this.state;
		return (
			<TouchableOpacity onPress={() => { this._sideCheckFn(goodsCateCode, goodsList); }} activeOpacity={0.5} style={styles.listSideRow}>
				<Text style={styles.listSideText}>{goodsCateName}</Text>
				{
					(index > 0 && !single) ? (< Text style={styles.selectNumber}>{index}</Text>) : null
				}
				{/* {selected ? <View style={{
					width: 12 * scale, height: 12 * scale,
					backgroundColor: '#fff', transform: [{ 'rotate': '45deg' }], position: 'absolute', right: -8
				}}></View> : null} */}
			</TouchableOpacity>
		);
	}

	//头部筛选输入框
	_renderFilterContent () {
		return (
			<TouchableOpacity activeOpacity={1} onPress={() => { this.refs.searchInput.focus() }} style={styles.searchBg}>
				<Image source={searchIcon} style={styles.searchImg} />
				<TextInput
					ref={'searchInput'}
					style={styles.searcuhInput}
					underlineColorAndroid='transparent'
					placeholder={this.props.placeholderText || '请输入分类名称'}
					onChangeText={(value) => {
						this._writeFn(value);
					}}
					onSubmitEditing={() => {
						this._searchFn();
					}}
					returnKeyType={'search'}
				/>
			</TouchableOpacity>
		)
	}

	_renderLeftBtns () {
		let { leftBtnIcon, leftBtnsList } = this.props;
		return (
			<View style={productSelectStyle.topBtns}>
				{
					leftBtnsList && leftBtnsList.length ?
						leftBtnsList.map((item, index) => {
							return <Text key={index} style={productSelectStyle.topBtnText} onPress={item.btnFun}>{item.btnText}</Text>
						}) : null
				}
				{leftBtnIcon ? <Image source={leftBtnIcon} style={productSelectStyle.topBtnIcon} /> : null}
			</View>
		)
	}

	_renderRightBtns () {
		let { rightBtnsList } = this.props;
		return (
			<View style={productSelectStyle.topBtns}>
				{
					rightBtnsList && rightBtnsList.length ?
						rightBtnsList.map((item, index) => {
							return <Text key={index} style={productSelectStyle.topBtnText} onPress={item.btnFun}>{item.btnText}</Text>
						}) : null
				}
			</View>
		)
	}

	render () {
		let { modalVisible, sideDataSource, mainDataSource, status, } = this.state;
		let { cancelPress, middleContent, renderLeft, renderRight, widthoutTop } = this.props;
		return (
			<Modal animationType={"fade"}
				transparent={true}
				onRequestClose={() => { console.log(1) }}
				visible={modalVisible}>
				<View style={styles.containerModal}>
					<TouchableOpacity activeOpacity={1} style={styles.bg} onPress={() => { cancelPress && cancelPress() }}>
					</TouchableOpacity>
					<View style={styles.listCell}>

						{
							!widthoutTop ?
								<View style={styles.searchBox}>
									{renderLeft ? renderLeft() : this._renderLeftBtns()}
									{middleContent ? middleContent() : this._renderFilterContent()}
									{renderRight ? renderRight() : this._renderRightBtns()}
								</View> : null
						}

						<View style={styles.listView}>
							{sideDataSource && sideDataSource.length > 0 ? (
								<View style={{ flex: 1, flexDirection: 'row' }}>
									<View style={styles.listSideWrap}>
										<FlatList
											extraData={this.state}
											style={styles.listSideView}
											data={sideDataSource}
											renderItem={this._renderSide}
										/>
									</View>
									<ScrollView
										horizontal={true}
										style={styles.listMainWrap}
									>
										{
											mainDataSource && mainDataSource.length > 0 ? (
												<FlatList
													extraData={this.state}
													style={styles.listMainView}
													data={mainDataSource}
													renderItem={this._renderMain}
												/>
											) : (
													<View style={{ width: 255 * scale }}>
														<PageStatusIndex status={'empty'} emptyText={'该类目暂时无子商品'} />
													</View>
												)
										}
									</ScrollView>
								</View>
							) : (<PageStatusIndex status={'empty'} emptyText={'暂无品类'} />)}
						</View>
					</View>
				</View>
			</Modal>
		);
	}

}


const styles = StyleSheet.create({
	containerModal: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		justifyContent: 'flex-end',
	},
	bg: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .3)',
	},
	listHead: {
		flexDirection: 'row',
		justifyContent: 'space-around',
		height: 52 * scale,
		width: 375 * scale,
		alignItems: 'center',
	},
	listHeadText: {
		fontSize: 16 * scale,
		color: style.color.themeColor,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 8 * scale,
		paddingRight: 8 * scale
	},
	listCell: {
		backgroundColor: '#fff',
		width: 375 * scale,
		height: '70%',
		borderRadius: 15 * scale
	},
	listView: {
		flex: 1,
		flexDirection: 'row',
		borderTopWidth: 1,
		borderTopColor: '#F4F7FE',
	},
	listSideWrap: {
		paddingBottom: 20 * scale,
		backgroundColor: '#F4F7FE',
	},
	listSideView: {
		width: 120 * scale,
	},
	listSideRow: {
		height: 50 * scale,
		justifyContent: 'center',
		alignItems: 'center',
		flexDirection: 'row'
	},
	listSideRowCur: {
		backgroundColor: '#fff',
	},
	listSideText: {
		fontSize: 13 * scale,
		color: '#000',
	},
	longText: {
		width: 160 * scale
	},
	listMainWrap: {
		paddingBottom: 20 * scale,
		backgroundColor: '#fff',
		width: 255 * scale,
	},
	listMainView: {
		width: 255 * scale,
		paddingLeft: 2 * scale,
		paddingRight: 20 * scale,
		backgroundColor: '#fff'
	},
	listMainRow: {
		alignItems: 'center',
		flexDirection: 'row',
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
		paddingLeft: 10 * scale,
	},
	optionPic: {
		width: 14 * scale,
		height: 14 * scale,
		marginLeft: 10 * scale,
		marginRight: 10 * scale
	},
	searchBox: {
		height: 55 * scale,
		paddingTop: 13 * scale,
		paddingBottom: 12 * scale,
		flexDirection: 'row',
		alignItems: 'center',
	},
	searchBg: {
		flex: 1,
		backgroundColor: '#F4F7FE',
		borderRadius: 4 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		marginLeft: 12 * scale,
		marginRight: 12 * scale,
		flexDirection: 'row',
		alignItems: 'center',
	},
	searchBtn: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
		marginLeft: 10 * scale,
		padding: 5 * scale
	},
	searchImg: {
		width: 11 * scale,
		height: 11 * scale,
		// marginRight: 12 * scale
	},
	searcuhInput: {
		paddingVertical: 0,
		height: 18 * scale,
		fontSize: 12 * scale,
		paddingLeft: 12 * scale,
		width: 170 * scale,
	},
	selectNumber: {
		borderRadius: 5 * scale,
		width: 20 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale,
		fontSize: 11 * scale,
		backgroundColor: style.color.themeColor,
		color: style.color.white,
		textAlign: 'center'
	},
	tips: {
		width: 15 * scale,
		height: 15 * scale,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderRadius: 2 * scale,

	},
	tipsText: {
		fontSize: 10 * scale
	},
	changeText: {
		color: style.color.fontRed1,
		fontSize: 12 * scale,
		paddingLeft: 5 * scale
	},
	deptText: {
		flex: 1,
		fontSize: 10 * scale,
		color: '#000',
		opacity: 0.5,
		textAlign: 'right'
	}
})